<?php


namespace app\admin\util;

use QL\QueryList;
use GuzzleHttp\Exception\RequestException;
use \Exception;

class CollectUtil
{
    public static function sendRequst($url)
    {
        $ql = QueryList::getInstance();
        for ($i = 0; $i < 3; $i++) {
            try {
                $q1 = $ql->get($url, null, ["timeout" => 30]);
            }catch(RequestException $e) {
                if($i==2){
                    throw new Exception("页面请求超时!");;
                }
                continue;
            }
            return $q1;
        }

    }

    public static function collect($url, $collectRule){
        $rules = json_decode($collectRule->rules, true);
        if($collectRule->type==RULE_TYPE_SIMPLE){
            return self::collect_type_simple($url,$collectRule->remove,$collectRule->encoding, $rules);
        }elseif($collectRule->type==RULE_TYPE_RANGE){
            return self::collect_type_range($url, $collectRule->remove,$collectRule->encoding,$rules,$collectRule->range,$collectRule->take);
        }
        return null;
    }

    public static function collect_type_simple($url, $remove,$encoding,$rules)
    {
        $q1 = self::sendRequst($url);
        if($remove){
            $q1->find($remove)->remove();
        }
        if($encoding){
            $q1->encoding('UTF-8',$encoding);
        }
        $result = [];
        foreach ($rules as $rule) {
            $ql_selector = $q1->find($rule['selector']);
            switch ($rule['attr']) {
                case "text":
                    $result[$rule["key"]] = $ql_selector->text();
                    break;
                case "texts":
                    $result[$rule["key"]] = $ql_selector->texts();
                    break;
                case "html":
                    $result[$rule["key"]] = $ql_selector->html();
                    break;
                default:
                    $result[$rule["key"]] = $ql_selector->attr($rule["attr"]);
            }
        }
        return $result;
    }
    public static function collect_type_range($url, $remove,$encoding,$rules_,$range,$take)
    {
        $q1=self::sendRequst($url);
        if($remove){
            $q1->find($remove)->remove();
        }
        if($encoding){
            $q1=$q1->encoding('UTF-8',$encoding)->removeHead();
        }
        $rules = [];
        foreach ($rules_ as $rule) {
            $rules[$rule['key']]=[$rule['selector'],$rule['attr']];
        }
        // 切片选择器$range
        $q1 = $q1->rules($rules);
        if($range){
            $q1=$q1->range($range);
        }
        $q1 = $q1->query()->getData();
        if($take){
            $q1=$q1->take($take);
        }
        return $q1->all();
    }
}